package respository

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/dto"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/vo"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type IFctRepository interface {
	Create(fct model.Fct)
	Update(fct model.Fct)
	SelectById(Id int)
	SelectFullFctById(Id int)
	DeleteById(Id int)
	List(fctList vo.FuncList)
}

type FctRepository struct {
	DB *gorm.DB
}

func (f FctRepository) Create(fct model.Fct)  (int, error){

	if err := f.DB.Create(&fct).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return 0, err
	}

	return fct.ID, nil
}

func (f FctRepository) Update(fct model.Fct) (*model.Fct, error){

	if err := f.DB.Updates(&fct).Error;err != nil {
		return nil, err
	}

	return &fct,nil
}

func (f FctRepository) SelectById(Id int) (fct *model.Fct, err error){

	if res := f.DB.First(&fct, Id);res.Error != nil{
		return nil, res.Error
	}

	return
}

func (f FctRepository) SelectFullFctById(Id int) *dto.FullFctDto{

	f.DB = f.DB.Where("fcts.id = ?", Id)
	selectSql := "fcts.id,fcts.name,fcts.page_id as page_id," +
		"pages.name as page_name,fcts.type,fcts.desc"
	joinsSql := "left join pages on fcts.page_id = pages.id"

	var fullFct dto.FullFctDto

	f.DB.Model(&model.Fct{}).Select(selectSql).Joins(joinsSql).
		Order("fcts.created_at desc").Scan(&fullFct)

	return &fullFct
}


func (f FctRepository) DeleteById(Id int) (rowsAffected int64) {

	rowsAffected = f.DB.Where("id = ?", Id).Delete(model.Fct{}).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return
}

func (f FctRepository) List(fctList vo.FuncList) (fullFcts []dto.FullFctDto, total int64){
	// 条件查询
	if fctList.PageId > 0  {
		f.DB = f.DB.Where("fcts.page_id = ?", fctList.PageId)
	}
	if fctList.ID > 0  {
		f.DB = f.DB.Where("fcts.id = ?", fctList.ID)
	}
	if fctList.Name != ""  {
		f.DB = f.DB.Where("fcts.name like ?", "%" + fctList.Name + "%")
	}
	if fctList.Type !="" {
		f.DB = f.DB.Where("fcts.type = ?", fctList.Type)
	}
	if fctList.PageNum == 0  {
		fctList.PageNum = 1
	}
	if fctList.PageSize == 0  {
		fctList.PageSize = 10
	}

	selectSql := "fcts.id,fcts.name,fcts.page_id as page_id," +
		"pages.name as page_name,fcts.type,fcts.desc"
	joinsSql := "left join pages on fcts.page_id = pages.id"

	//总记录数
	f.DB.Model(&model.Fct{}).Count(&total)

	f.DB.Model(&model.Fct{}).Select(selectSql).Joins(joinsSql).Order("fcts.created_at desc").
		Offset((fctList.PageNum -1) * fctList.PageSize).Limit(fctList.PageSize).Scan(&fullFcts)

	return
}

func NewFctRepository() FctRepository{
	db := common.GetDB()
	//db.AutoMigrate(model.Fct{})

	return FctRepository{DB: db}
}